﻿using System.Diagnostics;
using System;
using System.Linq;
using System.Collections.Generic;
namespace TSharp.Core.Util
{
    /// <summary>
    /// 
    /// </summary>
    /// <author>
    /// tangjingbo
    /// </author>
    /// <remarks>
    /// tangj15 at 2012-5-4 11:58
    /// </remarks>
    public class CMD
    {
        /// <summary>
        /// Runs the CMD.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="args">The args.</param>
        /// <returns></returns>
        public static string RunCmd(string command, params object[] args)
        {
            return RunCmds(string.Format(command, args));
        }
        /// <summary>
        /// Runs the CMDS.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns></returns>
        public static string RunCmds(params string[] command)
        {
            var process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = "/c \"" + BuildCommond(command) + "\"";
            Console.WriteLine(process.StartInfo.Arguments);
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            return process.StandardOutput.ReadToEnd();
        }
        /// <summary>
        /// Builds the commond.
        /// </summary>
        /// <param name="commands">The commands.</param>
        /// <returns></returns>
        public static string BuildCommond(string[] commands)
        {
            return string.Join(" && ", commands.Select(x => "\"" + x.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""));
        }
    }
}